package org.hawk.gwt.ppc.examples.methods;

import java.lang.reflect.Method;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
/**
 * Example for method invocation.
 *  
 * @author alex.bereznevatiy@gmail.com
 */
public class Methods implements EntryPoint {
	private Button alertMeButton;
	
	private Button addLabelButton;

	public void onModuleLoad() {
		final RootPanel rootPanel = RootPanel.get();

		alertMeButton = new Button();
		rootPanel.add(alertMeButton);
		alertMeButton.setText("Alert me!");
		alertMeButton.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				try {
					/*
					 * Class.forName() will work for proccessed classes and some related ones.
					 */
					Class<?> cls = Class.forName("org.hawk.gwt.ppc.examples.methods.MethodsSource");
					// getting method:
					Method m = cls.getMethod("alertMe", String.class);
					// And last step and still no difference from plain JVM:
					m.invoke(null, "This is alert text");
				}
				catch(Exception ex){
					GWT.log("Error!",ex);
				}
			}
		});
		
		addLabelButton = new Button();
		rootPanel.add(addLabelButton);
		addLabelButton.setText("Add Label");
		addLabelButton.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				try {
					/*
					 * Here we are using Constructor.newInstance() to create instances dynamically:
					 */
					Class<?> cls = Class.forName("org.hawk.gwt.ppc.examples.methods.MethodsSource");
					Object instance = cls.getConstructor(String.class).newInstance("My New Label");
					// And again calling the method in JVM reflection way:
					Method m = cls.getMethod("toLabel");
					rootPanel.add((Widget) m.invoke(instance));
				}
				catch(Exception ex){
					GWT.log("Error!",ex);
				}
			}
		});
	}

}
